package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public void save(Role role) {
        roleMapper.insert(role);
        List<Permission> permissions = role.getPermissions();
        for (Permission permission : permissions) {
            roleMapper.insertPermissionRelation(role.getId(),permission.getId());
        }
    }

    @Override
    public void update(Role role) {
        roleMapper.updateByPrimaryKey(role);
        roleMapper.deletePermissionRelation(role.getId());
        List<Permission> permissions = role.getPermissions();
        for (Permission permission : permissions) {
            roleMapper.insertPermissionRelation(role.getId(),permission.getId());
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        //1.查询记录总数
        int count =  roleMapper.query4Count(qo);
        if (count == 0) {
            return new PageResult(0,Collections.EMPTY_LIST);
        }
        List<Role> list = roleMapper.query4List(qo);
        //2.查询分页数据

        return new PageResult(count,list);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }
}
